"""
停车场数据分析系统安装脚本
"""

import os
import sys
import subprocess
import argparse
import getpass

def parse_args():
    """解析命令行参数"""
    parser = argparse.ArgumentParser(description='停车场数据分析系统安装脚本')
    parser.add_argument('--server', default='localhost', help='SQL Server服务器名称或IP地址')
    parser.add_argument('--user', default='sa', help='SQL Server用户名')
    parser.add_argument('--db', default='ParkingManagement', help='数据库名称')
    parser.add_argument('--skip-db-setup', action='store_true', help='跳过数据库设置')
    parser.add_argument('--skip-deps', action='store_true', help='跳过依赖项安装')
    
    return parser.parse_args()

def install_dependencies():
    """安装Python依赖项"""
    print("安装Python依赖项...")
    
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
        print("依赖项安装完成。")
    except subprocess.CalledProcessError as e:
        print(f"安装依赖项时出错: {e}")
        return False
    
    return True

def setup_database(server, user, password, db_name):
    """设置数据库"""
    print(f"正在设置数据库 {db_name} 在服务器 {server}...")
    
    # 构建sqlcmd命令
    create_cmd = [
        "sqlcmd", 
        "-S", server,
        "-U", user,
        "-P", password,
        "-i", os.path.join("sql", "create_database.sql")
    ]
    
    sample_cmd = [
        "sqlcmd", 
        "-S", server,
        "-U", user,
        "-P", password,
        "-i", os.path.join("sql", "insert_sample_data.sql")
    ]
    
    try:
        # 创建数据库和表
        print("创建数据库和表...")
        subprocess.check_call(create_cmd)
        
        # 插入示例数据
        print("插入示例数据...")
        subprocess.check_call(sample_cmd)
        
        print("数据库设置完成。")
    except subprocess.CalledProcessError as e:
        print(f"设置数据库时出错: {e}")
        return False
    
    return True

def update_config(server, user, password, db_name):
    """更新配置文件"""
    print("更新配置文件...")
    
    config_path = os.path.join("python", "config.py")
    
    try:
        with open(config_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 更新配置
        content = content.replace("'server': 'localhost'", f"'server': '{server}'")
        content = content.replace("'database': 'ParkingManagement'", f"'database': '{db_name}'")
        content = content.replace("'username': 'sa'", f"'username': '{user}'")
        content = content.replace("'password': '124113'", f"'password': '{password}'")
        
        with open(config_path, 'w', encoding='utf-8') as f:
            f.write(content)
            
        print("配置文件已更新。")
    except Exception as e:
        print(f"更新配置文件时出错: {e}")
        return False
    
    return True

def create_directories():
    """创建必要的目录"""
    dirs = [
        os.path.join("data", "export"),
        "logs"
    ]
    
    for d in dirs:
        os.makedirs(d, exist_ok=True)
    
    print("目录结构已创建。")
    return True

def run_test():
    """运行测试"""
    print("测试数据库连接...")
    
    try:
        result = subprocess.check_output([sys.executable, "-m", "python.main", "test"], 
                                        stderr=subprocess.STDOUT)
        print(result.decode('utf-8'))
        return True
    except subprocess.CalledProcessError as e:
        print(f"测试失败: {e.output.decode('utf-8')}")
        return False

def main():
    """主函数"""
    print("""
    =======================================================
         停车场数据分析系统 - 安装程序
    =======================================================
    """)
    
    args = parse_args()
    
    # 安装依赖项
    if not args.skip_deps:
        if not install_dependencies():
            sys.exit(1)
    
    # 设置数据库
    if not args.skip_db_setup:
        password = getpass.getpass(f"请输入 {args.user} 用户的密码: ")
        
        if not setup_database(args.server, args.user, password, args.db):
            sys.exit(1)
        
        if not update_config(args.server, args.user, password, args.db):
            sys.exit(1)
    
    # 创建目录
    if not create_directories():
        sys.exit(1)
    
    # 运行测试
    if not run_test():
        print("警告: 测试失败，但安装过程将继续。")
    
    print("""
    =======================================================
         安装完成!
    
    你现在可以运行系统:
        python -m python.main
        
    例如，生成日报表:
        python -m python.main report --type daily
        
    或测试硬件接口:
        python -m python.main hardware --demo
    =======================================================
    """)

if __name__ == "__main__":
    main() 